import json
from typing import Union, List, Dict, Set, Awaitable, Optional, Any
import tornado.escape
import asyncio
from vcat.server.base_handler import WebSocketHandler
from vcat.server.logger import ser_logger
from vcat.core.event_bus import event_bus_left
from vcat.core.event import (
    Event, EventType
)
from vcat.core.constant import (
    HandlerLevel,
    WhenHandlerError,
    HandlerCategory
)
from vcat.server.status_code import make_response, Code, WebSocketResp


class SocketHandler(WebSocketHandler):
    event_loop = False
    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:
        print('---msg---', message)

    def __init__(self, *args, **kwargs):
        super(SocketHandler, self).__init__(*args, **kwargs)
        event_bus_left.as_handler(category=HandlerCategory.GENERAL,
                                  event_type=None,
                                  level=HandlerLevel.ON_MAIN_HANDLER,
                                  error=WhenHandlerError.IGNORE
                                  )(self.on_event)

    def on_event(self, evt: Event):
        if self.event_loop is False:
            asyncio.set_event_loop(asyncio.new_event_loop())
            self.event_loop = True
        data = evt.data
        msg_type = evt.event_type
        if not data:
            return
        elif msg_type in (EventType.TIME, EventType.CONTRACT):
            return
        if isinstance(data, (str, int, float)):
            msg = data
        else:
            msg = data.to_dict()
        print(msg)
        msg_resp = WebSocketResp(
            msg_type=msg_type.name,
            msg_data=msg
        )
        self.write_message(
            msg_resp.to_dict()
        )
